# -*- coding: utf-8 -*-

from rest_framework import status
from rest_framework.response import Response
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.exceptions import ParseError

import logging
logger = logging.getLogger('bt_server')

from common.base_resful_view import BaseResfulView, QueryParameterNotPresentError
from common.pagination import PageNumberPagination
from app.models import BtResource
from app.serializers.resource import BtResourceBaseSerializer, BtResourceVerboseSerializer


class ResourceStatusListView(BaseResfulView):
    # queryset = BtResource.objects.filter(is_delete=False).order_by('-update_time')
    queryset = BtResource.objects.order_by('-update_time')
    serializer_class = BtResourceBaseSerializer
    pagination_class = PageNumberPagination

    def get(self, request, *args, **kwargs):
        """获取资源状态列表"""
        return self.list(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        """添加/修改资源状态"""

        name = self.get_data_parameter('name', value_type=str)
        category = self.get_data_parameter('category', value_type=str)

        try:
            instance = BtResource.objects.get(
                name=name, category=category,
            )
        except BtResource.DoesNotExist:
            serializer = self.get_serializer(data=request.data)
        else:
            serializer = self.get_serializer(instance, data=request.data, partial=False)

        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        return Response(serializer.data, status=status.HTTP_201_CREATED)

    def get_queryset(self):
        """重写获取数据"""
        filter_params = dict()

        try:
            # 文件名称
            filter_params['name__contains'] = self.get_query_parameter('nameLike', value_type=str)
        except QueryParameterNotPresentError:
            pass

        queryset = self.queryset.filter(**filter_params)
        return queryset



class ResourceStatusDetailView(BaseResfulView):
    queryset = BtResource.objects.all()
    serializer_class = BtResourceVerboseSerializer
    lookup_field = 'pk'

    def get(self, request, *args, **kwargs):
        """获取资源状态详情"""
        return self.retrieve(request, *args, **kwargs)

    def put(self, request, *args, **kwargs):
        """更新资源状态"""
        kwargs["partial"] = True
        return self.update(request, *args, **kwargs)

    def patch(self, request, *args, **kwargs):
        """局部更新资源状态操作"""
        return self.partial_update(request, *args, **kwargs)

    def delete(self, request, *args, **kwargs):
        """删除资源状态"""
        return self.destroy(request, *args, **kwargs)

    def perform_destroy(self, instance):
        instance.delete()
